package org.cmroot.certmaster.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import org.cmroot.certmaster.client.dialogs.ConfirmDialog;
import org.cmroot.certmaster.client.dialogs.SignDialog;
import org.cmroot.certmaster.client.widgets.ErrorLabel;
import org.cmroot.certmaster.shared.PKIServiceException;
import org.cmroot.certmaster.shared.dto.Pkcs10DTO;

import java.util.Iterator;
import java.util.List;


/**
 * Copyright (c) 2010 Andrey Domas <andrey.domas at gmail.com>.
 * *
 * This file is part of certmaster.
 * *
 * Certmaster is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * *
 * Certmaster is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 */

public class RequestsScreen extends BaseScreen implements ValueChangeHandler {

    @UiField
    Grid RequestsGrid;
    @UiField
    PushButton button_submit_new_request;
    @UiField
    TextArea req_text;
    @UiField
    VerticalPanel request;
    @UiField
    PushButton button_cancel_new_request;
    @UiField
    ErrorLabel errorLabel;
    @UiField
    PushButton buttonNewRequest;
    @UiField
    CheckBox onlyUnsigned;

    private static final String TEXT_SIGNED = "Signed";
    private static final String TEXT_UNSIGNED = "Unsigned";
    private static final String TEXT_ACTIONS = "Actions";
    private static final String TEXT_ACTIONS_SIGN = "Sign";
    private static final String TEXT_ACTIONS_REMOVE = "Remove";

    interface UserScreenUiBinder extends UiBinder<Widget, RequestsScreen> {
    }

    private static UserScreenUiBinder ourUiBinder = GWT.create(UserScreenUiBinder.class);


    public void onValueChange(ValueChangeEvent valueChangeEvent) {
        /*   if (History.getToken().equals("user_new_request")) {
            request.setVisible(true);
            link_new.setVisible(false);
        } else {
            req_text.setText(null);
            request.setVisible(false);
            link_new.setVisible(true);
        }*/
    }

    private void refreshRequestsGrid() {
        GWTClientService.App.getInstance().getRequests(
                new AsyncCallback<List<Pkcs10DTO>>() {

                    @Override
                    public void onFailure(Throwable caught) {
                        if (caught instanceof PKIServiceException) {
                            errorLabel.showError(caught.getMessage());
                        }
                    }

                    @Override
                    public void onSuccess(List<Pkcs10DTO> result) {
                        Iterator<Pkcs10DTO> li = result.iterator();
                        RequestsGrid.resizeRows(result.size() + 1);
                        int index = 0;
                        while (li.hasNext()) {
                            Pkcs10DTO c = li.next();
                            RequestsGrid.setText(++index, 0, String.valueOf(index));
                            RequestsGrid.setText(index, 1, c.getCN());
                            RequestsGrid.setText(index, 2, c.getChildCount() > 0 ? TEXT_SIGNED : TEXT_UNSIGNED);
                            RequestsGrid.setWidget(index, 3, addActions(c.getId()));
                        }
                    }
                }
        );
    }

    public RequestsScreen() {
        initWidget(ourUiBinder.createAndBindUi(this));

        onlyUnsigned.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
            @Override
            public void onValueChange(ValueChangeEvent<Boolean> booleanValueChangeEvent) {
                //To change body of implemented methods use File | Settings | File Templates.
            }
        });

        buttonNewRequest.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                errorLabel.resetError();
                request.setVisible(true); //show request form
                buttonNewRequest.setVisible(false);
            }
        });

        button_cancel_new_request.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                req_text.setText(null);
                request.setVisible(false);
                buttonNewRequest.setVisible(true);
            }
        });

        button_submit_new_request.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                request.setVisible(false);
                GWTClientService.App.getInstance().newRequest(req_text.getText(),
                        new AsyncCallback() {

                            @Override
                            public void onFailure(Throwable caught) {
                                if (caught instanceof PKIServiceException) {
                                    errorLabel.showError(caught.getMessage());
                                }
                            }

                            @Override
                            public void onSuccess(Object result) {
                                refreshRequestsGrid();
                            }
                        }
                );
                req_text.setText(null); //reset request data in request form
                buttonNewRequest.setVisible(true);
            }
        });

        refreshRequestsGrid();
    }

    private void signRequest(Long reqId) {
        SignDialog signDialog = new SignDialog(reqId);
        signDialog.show();
    }

    private void deleteRequest(final Long reqId) {

        ConfirmDialog deleteConfirmDialog = new ConfirmDialog();

        deleteConfirmDialog.setQuestion("Delete certificate request with id " + reqId + "?");

        deleteConfirmDialog.addConfirmHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                GWTClientService.App.getInstance().removePKCS(Pkcs10DTO.class.getName(), reqId, new AsyncCallback() {
                    @Override
                    public void onFailure(Throwable throwable) {
                        errorLabel.showError(throwable.getMessage());
                    }

                    @Override
                    public void onSuccess(Object o) {
                        refreshRequestsGrid();
                    }
                });
            }
        });

        deleteConfirmDialog.show();

    }

    private MenuBar addActions(final Long reqId) {

        MenuBar rootMenu = new MenuBar(false);
        MenuBar actionsMenu = new MenuBar(true);

        actionsMenu.addItem(TEXT_ACTIONS_SIGN, new Command() {
            @Override
            public void execute() {
                signRequest(reqId);
            }
        });

        actionsMenu.addItem(TEXT_ACTIONS_REMOVE, new Command() {
            @Override
            public void execute() {
                deleteRequest(reqId);
            }
        });

        rootMenu.addItem(TEXT_ACTIONS, actionsMenu);

        return rootMenu;
    }

}